package lbframework.bean.tableEx;

import javax.swing.SwingConstants;
import lbframework.bean.dialog.LBDialog;
import lbframework.bean.table.LBColumnTable;
import lbframework.bean.table.LBTable;
import lbframework.classe.Util;
import lbframework.remote.Arquivo;

public class LBTableExportacaoGUI extends LBDialog {

    private LBTable tblTabela = null;

    public LBTableExportacaoGUI() throws Exception {
        initComponents();

        centralizarForm();

        this.setModal(true);
    }

    public void exibirCampo() throws Exception {
        LBColumnTable[] colunas = new LBColumnTable[]{
            new LBColumnTable("", 40, false, SwingConstants.CENTER, true, null),
            new LBColumnTable("Campo", 180, true, SwingConstants.LEFT, false, null)
        };

        Object[][] dados = new Object[tblTabela.getColumnModel().getColumnCount()][colunas.length];

        for (int i = 0; i < tblTabela.getColumnModel().getColumnCount(); i++) {
            dados[i][0] = true;
            dados[i][1] = tblTabela.getColumnModel().getColumn(i).getHeaderValue().toString();
        }

        tblCampo.setModel(dados, colunas);

        tblCampo.requestFocus();
    }

    private void exportar() throws Exception {
        Util.validarCampoTela(this.getCampoObrigatorio());

        char delimitador = 0;

        if (optTabulacao.isSelected()) {
            delimitador = 9;
        } else if (optPontoVirgula.isSelected()) {
            delimitador = ';';
        } else if (optVirgula.isSelected()) {
            delimitador = ',';
        } else if (optEspaco.isSelected()) {
            delimitador = ' ';
        } else if (optOutros.isSelected()) {
            delimitador = txtDelimitador.getText().charAt(0);
        }

        Arquivo arq = new Arquivo(flcArquivo.getArquivo(), "w");

        String linha = "";

        for (int i = 0; i < tblTabela.getColumnModel().getColumnCount(); i++) {
            if (((Boolean) tblCampo.getValueAt(i, 0)).booleanValue()) {                
                linha += tblTabela.getColumnModel().getColumn(i).getHeaderValue().toString() + delimitador;
            }
        }

        arq.write(linha);

        for (int l = 0; l < tblTabela.getRowCount(); l++) {
            linha = "";

            for (int c = 0; c < tblTabela.getColumnCount(); c++) {
                if (((Boolean) tblCampo.getValueAt(c, 0)).booleanValue()) {                    
                    Object value = tblTabela.getValueAt(l, c);

                    if (value != null) {
                        linha += value.toString() + delimitador;

                    } else {
                        linha += delimitador;
                    }
                }
            }

            arq.write(linha);
        }

        arq.close();

        Util.exibirMensagem("Exportado com sucesso!", getTitle());
    }

    private void habilitarDelimitador() throws Exception {
        if (optOutros.isSelected()) {
            txtDelimitador.setEnabled(true);
            txtDelimitador.setObrigatorio(true);
        } else {
            txtDelimitador.setEnabled(false);
            txtDelimitador.setObrigatorio(false);
            txtDelimitador.setText("");
        }
    }

    private void selecionarTodos() throws Exception {
        for (int i = 0; i < tblCampo.getRowCount(); i++) {
            tblCampo.setValueAt(chkTodos.isSelected(), i, 0);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btgDelimitador = new lbframework.bean.buttonGroup.LBButtonGroup();
        vRPanel2 = new lbframework.bean.panel.LBPanel();
        btnSair = new lbframework.bean.button.LBButton();
        btnExportar = new lbframework.bean.button.LBButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCampo = new lbframework.bean.table.LBTable();
        vRPanel1 = new lbframework.bean.panel.LBPanel();
        optTabulacao = new lbframework.bean.radioButton.LBRadioButton();
        optPontoVirgula = new lbframework.bean.radioButton.LBRadioButton();
        optVirgula = new lbframework.bean.radioButton.LBRadioButton();
        optEspaco = new lbframework.bean.radioButton.LBRadioButton();
        optOutros = new lbframework.bean.radioButton.LBRadioButton();
        txtDelimitador = new lbframework.bean.textField.LBTextField();
        vRPanel3 = new lbframework.bean.panel.LBPanel();
        flcArquivo = new lbframework.bean.fileChooser.LBFileChooser();
        chkTodos = new lbframework.bean.checkBox.LBCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Exportação para arquivo");

        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/sair.png"))); // NOI18N
        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/exportar.png"))); // NOI18N
        btnExportar.setText("Exportar");
        btnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout vRPanel2Layout = new javax.swing.GroupLayout(vRPanel2);
        vRPanel2.setLayout(vRPanel2Layout);
        vRPanel2Layout.setHorizontalGroup(
            vRPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, vRPanel2Layout.createSequentialGroup()
                .addContainerGap(247, Short.MAX_VALUE)
                .addComponent(btnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        vRPanel2Layout.setVerticalGroup(
            vRPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(vRPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        tblCampo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tblCampo);

        vRPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Delimitador"));

        btgDelimitador.add(optTabulacao);
        optTabulacao.setSelected(true);
        optTabulacao.setText("Tabulação");
        optTabulacao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optTabulacaoActionPerformed(evt);
            }
        });

        btgDelimitador.add(optPontoVirgula);
        optPontoVirgula.setText("Ponto e vírgula");
        optPontoVirgula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optPontoVirgulaActionPerformed(evt);
            }
        });

        btgDelimitador.add(optVirgula);
        optVirgula.setText("Vírgula");
        optVirgula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optVirgulaActionPerformed(evt);
            }
        });

        btgDelimitador.add(optEspaco);
        optEspaco.setText("Espaço");
        optEspaco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optEspacoActionPerformed(evt);
            }
        });

        btgDelimitador.add(optOutros);
        optOutros.setText("Outros:");
        optOutros.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optOutrosActionPerformed(evt);
            }
        });

        txtDelimitador.setColumns(1);
        txtDelimitador.setEnabled(false);
        txtDelimitador.setMascara("");

        javax.swing.GroupLayout vRPanel1Layout = new javax.swing.GroupLayout(vRPanel1);
        vRPanel1.setLayout(vRPanel1Layout);
        vRPanel1Layout.setHorizontalGroup(
            vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(vRPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(optTabulacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(optPontoVirgula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(optVirgula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(optEspaco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(vRPanel1Layout.createSequentialGroup()
                        .addComponent(optOutros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDelimitador, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(62, Short.MAX_VALUE))
        );
        vRPanel1Layout.setVerticalGroup(
            vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(vRPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(optTabulacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(optPontoVirgula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(optVirgula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(optEspaco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(optOutros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDelimitador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(68, Short.MAX_VALUE))
        );

        vRPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Arquivo"));

        flcArquivo.setDialogType("Save");
        flcArquivo.setObrigatorio(true);

        javax.swing.GroupLayout vRPanel3Layout = new javax.swing.GroupLayout(vRPanel3);
        vRPanel3.setLayout(vRPanel3Layout);
        vRPanel3Layout.setHorizontalGroup(
            vRPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, vRPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(flcArquivo, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
                .addContainerGap())
        );
        vRPanel3Layout.setVerticalGroup(
            vRPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(vRPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(flcArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        chkTodos.setSelected(true);
        chkTodos.setText("Selecionar todos");
        chkTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkTodosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(vRPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(vRPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(chkTodos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(vRPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(vRPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(chkTodos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE))
                    .addComponent(vRPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(vRPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        try {
            sair();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarActionPerformed
        try {
            exportar();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_btnExportarActionPerformed

    private void optTabulacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optTabulacaoActionPerformed
        try {
            habilitarDelimitador();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_optTabulacaoActionPerformed

    private void optPontoVirgulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optPontoVirgulaActionPerformed
        try {
            habilitarDelimitador();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_optPontoVirgulaActionPerformed

    private void optVirgulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optVirgulaActionPerformed
        try {
            habilitarDelimitador();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_optVirgulaActionPerformed

    private void optEspacoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optEspacoActionPerformed
        try {
            habilitarDelimitador();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_optEspacoActionPerformed

    private void optOutrosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optOutrosActionPerformed
        try {
            habilitarDelimitador();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_optOutrosActionPerformed

    private void chkTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkTodosActionPerformed
        try {
            selecionarTodos();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_chkTodosActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private lbframework.bean.buttonGroup.LBButtonGroup btgDelimitador;
    private lbframework.bean.button.LBButton btnExportar;
    private lbframework.bean.button.LBButton btnSair;
    private lbframework.bean.checkBox.LBCheckBox chkTodos;
    private lbframework.bean.fileChooser.LBFileChooser flcArquivo;
    private javax.swing.JScrollPane jScrollPane1;
    private lbframework.bean.radioButton.LBRadioButton optEspaco;
    private lbframework.bean.radioButton.LBRadioButton optOutros;
    private lbframework.bean.radioButton.LBRadioButton optPontoVirgula;
    private lbframework.bean.radioButton.LBRadioButton optTabulacao;
    private lbframework.bean.radioButton.LBRadioButton optVirgula;
    private lbframework.bean.table.LBTable tblCampo;
    private lbframework.bean.textField.LBTextField txtDelimitador;
    private lbframework.bean.panel.LBPanel vRPanel1;
    private lbframework.bean.panel.LBPanel vRPanel2;
    private lbframework.bean.panel.LBPanel vRPanel3;
    // End of variables declaration//GEN-END:variables

    public LBTable getTblTabela() {
        return tblTabela;
    }

    public void setTblTabela(LBTable tblTabela) {
        this.tblTabela = tblTabela;
    }
}
